package org.groupg.practice;

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.util.List;

/**
 * CSV文件写入工具类
 */
public class CsvWriterUtil {
    private static final Logger logger = LoggerFactory.getLogger(CsvWriterUtil.class);

    /**
     * 写入CSV文件
     * @param filePath 文件路径
     * @param dataList 数据列表
     * @param separator 字段分隔符
     * @param lineEnd 行结束符
     */
    public static <T> void writeCsv(String filePath, List<T> dataList,
                                   char separator, String lineEnd) {
        try (FileWriter writer = new FileWriter(filePath)) {
            logger.info("开始写入CSV文件: {}", filePath);

            // 配置列映射策略
            ColumnPositionMappingStrategy<T> strategy = new ColumnPositionMappingStrategy<>();
            strategy.setType((Class<? extends T>) dataList.get(0).getClass());
            strategy.setColumnMapping("name", "age", "email");

            // 构建CSV写入器
            StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
                .withMappingStrategy(strategy)
                .withSeparator(separator)
                .withLineEnd(lineEnd)
                .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                .build();

            // 写入数据
            beanToCsv.write(dataList);

            logger.info("成功写入 {} 条记录到文件: {}", dataList.size(), filePath);
        } catch (Exception e) {
            logger.error("写入CSV文件失败: {}", filePath, e);
            throw new CsvOperationException("CSV写入失败", e);
        }
    }
}

/**
 * 自定义CSV操作异常
 */
class CsvOperationException extends RuntimeException {
    public CsvOperationException(String message, Throwable cause) {
        super(message, cause);
    }
}